<?php
namespace Api\Controller;
use Think\Controller;
class CommonController extends Controller {
    // public $info_id;
    public function _initialize(){
        $map['appid'] = $_GET['token'];
        $wechat = M("Wechat")->where($map)->find();
        $wid = M("Wechat")->where($map)->getField("wid");
        if($wechat){
            $shop = M("shop")->where(['shop_id'=>$wechat['shop_id']])->find();
            //独立生成的小程序
            if($shop['has_mini']){
                session('wid',$wechat['wid']);
            }else{
                session('wid',$wid);
            }
        }else{
            if($wid){
                session('wid',$wid);
            }else{
                $this->error('你访问的页面不存在！');
            }
        }
    }

    //获取微信公众平台token
    public function get_access_token_mp()
    {
        $wid = session('wid');
        $wechat = M('wechat')->where(array('wid'=>$wid))->find();
        $token = S("access_token_mp");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat['appid']}&secret={$wechat['app_secret']}";
        $res = $this->ihttp_get($url);
        $td = json_decode($res, true);
        if($td['access_token']){
            S("access_token_mp", $td['access_token'], $td['expires_in'] - 120);
            return $td['access_token'];
        }else{
            return false;
        }
    }

    public function getShopOrder($shop_id){
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();

        //$price = $wechat['shop_fee'];
        if($_POST['join_fee'] == '无需置顶'){
            $join_fee = 0;
            $join_days = 0;
        }else{
            $top = M("Join")->where($map)->select();
            foreach ($top as $k => $v) {
                if($v['title'] == $_POST['join_fee']){
                    $join_fee = $v['price'];
                    $join_days = $v['days'];
                }
            }
        }
        $all_money = $join_fee;
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $data['wid'] = session('wid');
        $data['shop_id'] = $shop_id;
        $data['openid'] = $_POST['openid'];
        $data['out_trade_no'] = $this->build_order_no();
        $data['title'] = "商家入驻";
        $data['remark'] = $_POST['name'];
        $data['price'] = $join_fee;
        $data['pay_money'] = $all_money;
        $data['join_days'] = $join_days;
        $data['status'] = 0;
        $data['is_pay'] = 0;
        $data['create_time'] = date("Y-m-d H:i:s");
        if(!$log_id = M("ShopOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        if($all_money <= 0){
            $eq['id'] = $log_id;
            M("ShopOrder")->where($eq)->setField('is_pay',1);
            return false;
        }
        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/index",array('type'=>'shop'));
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['title']);
        $input->SetAttach($data['title']);
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($data['pay_money']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        //积分产生
        $pro = M('credit_setint')->where(['wid' => session('wid')])->find();
        $credit = $data['pay_money'] * $pro['shop_in'];
        addCredit($_POST['openid'], $credit, $log_id, session('wid'), 0);

        echo $jsApiParameters;
        exit();
    }

    public function renewShopOrder($shop_id){
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();

        //$price = $wechat['shop_fee'];
        
        $top = M("Join")->where(array('id'=>$_POST['join_id']))->find();
        
        $join_fee = $top['price'];
        $join_days = $top['days'];
         
        
        $all_money = $join_fee;
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $data['wid'] = session('wid');
        $data['shop_id'] = $shop_id;
        $data['openid'] = $_POST['openid'];
        $data['out_trade_no'] = $this->build_order_no();
        $data['title'] = "商家入驻";
        $data['remark'] = $_POST['name'];
        $data['price'] = $join_fee;
        $data['pay_money'] = $all_money;
        $data['join_days'] = $join_days;
        $data['status'] = 0;
        $data['is_pay'] = 0;
        $data['create_time'] = date("Y-m-d H:i:s");
        if(!$log_id = M("ShopOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        if($all_money <= 0){
            $eq['id'] = $log_id;
            M("ShopOrder")->where($eq)->setField('is_pay',1);
            return false;
        }
        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/renewShop",array('type'=>'shop'));
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['title']);
        $input->SetAttach($data['title']);
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($data['pay_money']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);
        
        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        echo $jsApiParameters;
        exit();
    }
    public function getInfoOrder($info_id){
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();

        $price = $wechat['tongcheng_fee'];
        
        if($_POST['top_fee'] == '无需置顶'){
            $top_fee = 0;
            $top_days = 0;
        }else{
            $top = M("Top")->where($map)->select();
            foreach ($top as $k => $v) {
                if($v['title'] == $_POST['top_fee']){
                    $top_fee = $v['price'];
                    $top_days = $v['days'];
                }
            }
        }
        $all_money = $price + $top_fee;
        //收费
        if($all_money>0){
            //是否开通同城卡
            $openid = I('openid');
            $card = M('card_log')->where(['wid' => session('wid'), 'openid' => $openid, 'end_time' => ['GT', date('Y-m-d H:i:s', time())], 'is_pay' => 1])
                    ->order('id desc')->select();
            $cardinfo = M('card')->where(['id'=>$card['id']])->find();
            if($card){
                //优惠方式
                if($cardinfo['is_fee']){
                    //便宜多少钱
                    $all_money = $cardinfo['tie_fee'] + $top_fee;
                }
                if($cardinfo['is_num']){
                    //包条
                    //发了多少条(从开通卡的时间算)
                    $eq['wid']= session('wid');
                    $eq['openid'] =$openid;
                    //$eq['is_pay'] = 1;
                    $eq['create_time'] = ['gt',$card['create_time']];
                    $count = M('info_order')->where($eq)->count();
                    if($count > $cardinfo['tie_num']){
                        //条数超了，原价付钱
                        $all_money = $price + $top_fee;
                    }else{
                        $all_money = $top_fee;
                    }
                }
            }else{
                //没开通，按原来收费
                $all_money = $all_money;
            }
        }
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $data['wid'] = session('wid');
        $data['cid'] = $_GET['cid'];
        $data['sub_cid'] = $_GET['sub_cid'];
        $data['action'] = strtolower(CONTROLLER_NAME);
        $data['type'] = $_GET['type'];
        $data['sub_type'] = $_GET['sub_type']?$_GET['sub_type']:0;
        $data['info_id'] = $info_id;
        $data['openid'] = $_POST['openid'];
        $data['out_trade_no'] = $this->build_order_no();
        $data['title'] = "同城信息";
        $data['remark'] = "";
        $data['price'] = $price;
        $data['top_fee'] = $top_fee;
        $data['top_days'] = $top_days;
        $data['pay_money'] = $all_money;
        $data['status'] = 0;
        $data['is_pay'] = 0;
        $data['create_time'] = date("Y-m-d H:i:s");
        if(!$log_id = M("InfoOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        if($all_money <= 0){
            $eq['id'] = $log_id;
            M("InfoOrder")->where($eq)->setField('is_pay',1);
            return false;
        }
        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/index",array('type'=>'info'));
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['title']);
        $input->SetAttach($data['title']);
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($data['pay_money']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        //积分产生
        $pro = M('credit_setint')->where(['wid' => session('wid')])->find();
        $credit = $data['pay_money'] * $pro['release'];
        addCredit($_POST['openid'], $credit, $log_id, session('wid'), 2);

        echo $jsApiParameters;
        exit();
    }

    public function setTopInfo($id,$action,$openid,$name){
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();


        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];
        $topInfo = M('top')->where(array('title'=>$name))->find();
        $out_trade_no = $this->build_order_no();
        $title = "发布置顶";
        $data = array();
        $data['wid'] = session('wid');
        $data['action'] = $action;
        $data['info_id'] = $id;
        $data['openid'] = $openid;
        $data['out_trade_no'] = $out_trade_no;
        $data['title'] = $title;
        $data['remark'] = "";
        $data['price'] = $topInfo['price'];
        $data['top_fee'] = $topInfo['price'];
        $data['top_days'] = $topInfo['days'];
        $data['pay_money'] = $topInfo['price'];
        $data['status'] = 0;
        $data['is_pay'] = 0;
        $data['is_top'] = 1;
        $data['create_time'] = date("Y-m-d H:i:s");
        if(!$log_id = M("InfoOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }


        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/setTop");
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($title);
        $input->SetAttach($title);
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee(($topInfo['price']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        echo $jsApiParameters;
        exit();
    }

    protected function ihttp_post($url, $post_data){
    	$ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    protected function ihttp_get($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    protected function build_order_no(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    protected function getAnnounceTime($time){
        $timestamp = time() - strtotime($time);
        if($timestamp < 3600){
            $str = floor($timestamp/60);
            if($str < 1){
                $str = 1;
            }
            $str .= "分钟前";
        }else if($timestamp >= 3600 && $timestamp <86400){
            $str = floor($timestamp/3600)."小时前";
        }else if($timestamp >= 86400){
            $str = floor($timestamp/86400);
            if($str > 30){
                $str = 30;
            }
            $str .= "天前";
        }
        return $str;
    }
    public function handleVideoUrl($url){
        /*$begin = strpos($url,'vid=');
        $end = strpos($url,'tiny=');
        $length = $end - $begin;
        $vid = substr($url,$begin + 4,$length - 9);
        */
        $begin = strpos($url,'vid=');
        $vid = substr($url,$begin+4 ,11 );
        $curl_url = "http://vv.video.qq.com/getinfo?vids=".$vid."&platform=101001&charge=0&otype=json";
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $curl_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        $cut_json = substr($output,strpos($output,'=')+1);
        $second_cut_json = substr($cut_json,0,strlen($cut_json) - 1);
        $arr = json_decode($second_cut_json,true);
        $arr_url = $arr['vl']['vi'][0]['ul']['ui'][0]['url'];
        $arr_fn = $arr['vl']['vi'][0]['fn'];
        $arr_fvkey = $arr['vl']['vi'][0]['fvkey'];
        $video_url = $arr_url.$arr_fn.'?vkey='.$arr_fvkey;
        return $video_url;
    }
    /*
     * 365小票打印
     *
     * */
    protected function sendSelfFormatOrderInfo($device_no,$key,$times,$orderInfo){ // $times打印次数
        $selfMessage = array(
            'deviceNo'=>$device_no,
            'printContent'=>$orderInfo,
            'key'=>$key,
            'times'=>$times
        );
        $url = "http://open.printcenter.cn:8080/addOrder";
        $options = array(
            'http' => array(
                'header' => "Content-type: application/x-www-form-urlencoded ",
                'method'  => 'POST',
                'content' => http_build_query($selfMessage),
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }
}